package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    private String shopAddress = "广东省江门市蓬江区潮连大道江门职业技术学院";

    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript ORDER_LIST;

    static {
        ORDER_LIST = new DefaultRedisScript<>();
        ORDER_LIST.setLocation(new ClassPathResource("orderNumber.lua"));
    }

    //单线程线程池
    private static final ExecutorService ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
    @PostConstruct
    private void init() {
        ORDER_EXECUTOR.submit(new SaveOrder());
    }

    /**
     * 用户下单
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //查地址簿获取用户信息
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(address.getCityName() + address.getDistrictName() + address.getDetail());
        //打包信息插入order表和order_detail表
        Orders orders = new Orders();
        //这两玩意老是装配不上，手动装配一下
        orders.setTablewareNumber(ordersSubmitDTO.getTablewareNumber());
        orders.setTablewareStatus(ordersSubmitDTO.getTablewareStatus());
        BeanUtils.copyProperties(address, orders);
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        LocalDateTime orderTime = LocalDateTime.now();

        //订单号使用缓存保存，每天凌晨0点更新，订单号再次从1开始,需要lua脚本执行
        Long orderNumber = redisTemplate.opsForValue().increment("orderNumber", 1);

        orders.setNumber(orderNumber.toString());
        orders.setStatus(orders.PAID);
        orders.setPayStatus(orders.UN_PAID);
        orders.setOrderTime(orderTime);
        //执行脚本，把订单数据放入缓存
        String jsonStr = JSONUtil.toJsonStr(orders);
        stringRedisTemplate.execute(
                ORDER_LIST,
                Collections.emptyList(),
                jsonStr
        );
        //插入数据库使用异步执行
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orders.getId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findAll(BaseContext.getCurrentId());
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetailMapper.insert(orderDetail);
        }
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    private class SaveOrder implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    if (list==null||list.isEmpty()) continue;
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    String jsonStr = JSONUtil.toJsonStr(value);
                    String s = jsonStr.substring(10, jsonStr.length() - 2);
                    String res = StringEscapeUtils.unescapeJava(s);
                    Orders orders1 = JSONUtil.toBean(res, Orders.class);
                    orderMapper.insert(orders1);
                } catch (Exception e) {
                    log.info("读消息队列出现异常{}",e);
                }
            }
        }
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        Orders orders = Orders.builder()
//                .number(ordersPaymentDTO.getOrderNumber())
//                .payMethod(ordersPaymentDTO.getPayMethod())
//                .payStatus(Orders.PAID)
//                .status(Orders.TO_BE_CONFIRMED)
//                .checkoutTime(LocalDateTime.now()).build();
//        //更改支付状态,订单状态，插入支付方式,结账时间
//        orderMapper.update(orders);
//        OrderPaymentVO paymentVO = new OrderPaymentVO();
//        UUID uuid = UUID.randomUUID();
//        paymentVO.setTimeStamp(LocalDateTime.now().toString());
//        paymentVO.setNonceStr(uuid.toString());
//        paymentVO.setPackageStr(orders.getPayStatus().toString());
//        paymentVO.setPaySign("ORDERPAID");
//        paymentVO.setSignType("RSA");
//        return paymentVO;
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

//调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

// 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端推送消息
        Map map = new HashMap<>();
        map.put("type", 1);//1 来单 2 催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 用户催单
     */
    @Override
    public void remin(Long id) {
        //根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        //校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //通过websocket向客户端推送消息
        Map map = new HashMap<>();
        map.put("type", 2);//1 来单 2 催单
        map.put("orderId", id);
        map.put("content", "订单号:" + ordersDB.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 再来一单
     */
    @Override
    public void repetition(Long id) {
        //添加到购物车
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        ShoppingCart shoppingCart = new ShoppingCart();
        for (OrderDetail orderDetail : orderDetailList) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.add(shoppingCart);
        }
    }

    /**
     * 历史订单查询
     */
    @Override
    public PageResult historyOrders(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        PageResult pageResult = new PageResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        OrderVO orderVO = new OrderVO();
        for (Orders orders : ordersPage) {
            List<OrderDetail> details = orderDetailMapper.getByOrderId(orders.getId());
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(details);
            orderVOList.add(orderVO);
        }
        return new PageResult(pageResult.getTotal(), orderVOList);

    }

    /**
     * 取消订单
     */
    @Override
    public void cancel(Long id) throws Exception {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //接单后不能取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orderMapper.update(orders);
    }

    /**
     * 查询订单详情
     */
    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 订单搜索
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //分页查询出所有订单
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> ordersList = ordersPage.getResult();
        //结果返回集合
        List<OrderVO> orderVOList = new ArrayList<>();

        //打包信息
        OrderVO orderVO = new OrderVO();
        for (Orders orders : ordersList) {
            //订单表相同字段拷贝
            BeanUtils.copyProperties(orders, orderVO);

            //订单细节
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
            orderVO.setOrderDetailList(orderDetailList);

            List<String> orderDishes = new ArrayList<>();
            //菜品信息拼接成字符串 "菜品名称*数量;菜品名称*数量;菜品名称*数量;" 的形式
            for (OrderDetail orderDetail : orderDetailList) {

                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                orderDishes.add(name);
                orderDishes.add("*");
                orderDishes.add(number.toString());
                orderDishes.add(";");
            }
            String orderDishesStr = String.join("", orderDishes);
            orderVO.setOrderDishes(orderDishesStr);
            orderVOList.add(orderVO);
        }

        PageResult pageResult = new PageResult(ordersPage.getTotal(), orderVOList);

        return pageResult;
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //2待接单
        Integer toBeConfirmed = orderMapper.statusCount(Orders.TO_BE_CONFIRMED);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        //3已接单 待派送就是已经接单未派送
        Integer confirmed = orderMapper.statusCount(Orders.CONFIRMED);
        orderStatisticsVO.setConfirmed(confirmed);
        //4派送中
        Integer deliveryInProgress = orderMapper.statusCount(Orders.DELIVERY_IN_PROGRESS);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 接单
     */
    @Override
    public void confirm(Orders orders) {
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        Orders orderDB = orderMapper.getById(ordersRejectionDTO.getId());
        Integer status = orderDB.getStatus();
        Orders orders = new Orders();
        //待付款
        if (status >= Orders.TO_BE_CONFIRMED && status != null) {//已付款 需要退款
            orders.setId(ordersRejectionDTO.getId());
            orders.setStatus(Orders.CANCELLED);
            //orders.setCancelReason("商家拒单");
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setCancelTime(LocalDateTime.now());
            //退款
            weChatPayUtil.refund(
                    orderDB.getNumber(),
                    orderDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 取消订单
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //接单后不能取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders != null && Objects.equals(orders.getStatus(), Orders.CONFIRMED)) {
            Orders orders1 = new Orders();
            orders1.setId(id);
            orders1.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orderMapper.update(orders1);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 完成订单
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders != null && Objects.equals(orders.getStatus(), Orders.DELIVERY_IN_PROGRESS)) {
            Orders orders1 = new Orders();
            orders1.setId(id);
            orders1.setStatus(Orders.COMPLETED);
            orders1.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(orders1);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}




















